import { ref, reactive, computed, watch } from 'vue';
import { message } from 'ant-design-vue';

/**
 * Table数据管理的hook
 * 负责数据加载、分页、排序、过滤等
 * @param {Object} options - 配置选项
 * @returns {Object} - 返回状态和方法
 */
export function useTableData(options) {
  const {
    fetchApi, // 获取列表数据的API函数
    queryParams = {}, // 查询参数
    defaultParams = {}, // 默认请求参数
    pagination: paginationOptions = true, // 分页配置
    immediate = true, // 是否立即加载数据
    transformResponse = null, // 转换响应数据的函数
    autoHandleError = true, // 是否自动处理错误
    defaultPageSize = 10, // 默认分页大小
    defaultCurrent = 1, // 默认当前页
  } = options || {};

  // 数据状态
  const dataList = ref([]);
  const loading = ref(false);
  const error = ref(null);
  const refresh = ref(0); // 用于触发刷新

    // // 查询参数
    // const queryParams = reactive({
    //   ...defaultParams,
    // });

  // 排序和过滤状态
  const sorter = ref({});
  const filters = ref({});

  // 分页配置
  const pagination = reactive(
    paginationOptions === false
      ? false
      : {
          current: defaultCurrent,
          pageSize: defaultPageSize,
          total: 0,
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total) => `共 ${total} 条`,
          ...(typeof paginationOptions === 'object' ? paginationOptions : {}),
        }
  );

  // 加载数据
  const loadData = async (params = {}) => {
    console.log(queryParams,'loadData');
    
    if (!fetchApi) return;

    loading.value = true;
    error.value = null;

    try {
      // 构建请求参数
      const requestParams = {
        ...queryParams,
        ...params,
      };

      // 添加分页参数
      if (pagination !== false) {
        requestParams.page = pagination.current;
        requestParams.pageSize = pagination.pageSize;
      }

      // 添加排序参数
      if (sorter.value.field) {
        requestParams.sortField = sorter.value.field;
        requestParams.sortOrder = sorter.value.order;
      }

      // 添加过滤参数
      if (Object.keys(filters.value).length) {
        requestParams.filters = filters.value;
      }

      const response = await fetchApi(requestParams);

      // 转换响应数据
      const responseData = transformResponse
        ? transformResponse(response)
        : response.data;

      // 更新数据和分页信息
      if (pagination !== false && responseData && responseData.list) {
        dataList.value = responseData.list;
        pagination.total = responseData.total || 0;
      } else {
        dataList.value = Array.isArray(responseData) ? responseData : responseData?.data || [];
      }

      return responseData;
    } catch (err) {
      error.value = err;
      if (autoHandleError) {
        message.error(err.message || '加载数据失败');
      }
      throw err;
    } finally {
      loading.value = false;
    }
  };

  // 处理表格变化
  const handleTableChange = ( tablePagination, tableFilters, tableSorter ) => {
    // 更新分页
    console.log(tablePagination,tableFilters,tableSorter);
    
    if (pagination !== false && tablePagination) {
      pagination.current = tablePagination.current;
      pagination.pageSize = tablePagination.pageSize;
    }

    // 更新过滤和排序
    // filters.value = tableFilters;
    // sorter.value = tableSorter;

    // 重新加载数据
    loadData();
  };

  // 设置查询参数并重新加载
  const setParams = (params = {}) => {
    Object.keys(params).forEach((key) => {
      queryParams[key] = params[key];
    });

    // 重置到第一页
    if (pagination !== false) {
      pagination.current = 1;
    }

    // 重新加载数据
    loadData();
  };

  // 刷新数据
  const refreshData = (resetPagination = false) => {
    if (resetPagination && pagination !== false) {
      pagination.current = 1;
    }
    refresh.value += 1;
    return loadData();
  };

  // 清空数据
  const clearData = () => {
    dataList.value = [];
    if (pagination !== false) {
      pagination.total = 0;
    }
  };

  // 监听refresh变化，触发数据加载
  watch(refresh, () => {
    loadData();
  });

  // 立即加载数据
  if (immediate && fetchApi) {
    loadData();
  }

  return {
    // 状态
    dataList,
    loading,
    error,
    pagination,
    // queryParams,
    sorter,
    filters,

    // 方法
    loadData,
    refreshData,
    clearData,
    setParams,
    handleTableChange,
  };
}
